package com.qfedu.mall.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qfedu.mall.beans.entity.User;
import com.qfedu.mall.beans.entity.Users;
import com.qfedu.mall.common.utils.JwtUtils;
import com.qfedu.mall.common.utils.MD5utils;
import com.qfedu.mall.common.vo.PageVo;
import com.qfedu.mall.common.vo.ResStatus;
import com.qfedu.mall.common.vo.ResultVO;
import com.qfedu.mall.common.vo.ResultVO1;
import com.qfedu.mall.mapper.UserDao;
import com.qfedu.mall.mapper.UsersMapper;
import com.qfedu.mall.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author dyw
 * @Date 2021年12月02日 10:19
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private UserDao userDao;

    @Autowired
    private UsersMapper usersMapper;


    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public ResultVO getUserInfo(Integer userId) {
        User user = userDao.selectUserById(userId);
        ResultVO resultVO = new ResultVO(ResStatus.OK, "Success", user);
        return resultVO;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public ResultVO login(String username, String password) {

        System.out.println(""+username);
        System.out.println(password);

        Users users1 = userDao.getUserByName(username);
        System.out.println(users1);
        if (users1 == null) {
            return new ResultVO(10001, "登录失败，用户名不存在！", null);
        } else {

            String md5Pwd = MD5utils.md5(password);
            if (md5Pwd.equals(users1.getPassword())) {

                String token = JwtUtils.createToken(users1.getUsername(), UUID.randomUUID().toString());
                return new ResultVO(10000, token, users1);
            } else {
                return new ResultVO(10001, "登录失败，密码错误！", null);
            }

        }

    }

    @Override
    public ResultVO regist(String username, String password,String nickName) {
        //            //1.根据用户查询，这个用户是否已经被注册
        Users usersCondition = new Users();
        usersCondition.setUsername(username);
        Users user = userDao.getUserByName(username);
        //2.如果没有被注册则进行保存操作
        if (user == null) {
            String md5Pwd = MD5utils.md5(password);
            Users user1 = new Users();
            user1.setUsername(username);
            user1.setPassword(md5Pwd);
            user1.setNickname(nickName);
            int i = userDao.insertUsers(user1);
            if (i > 0) {
                return new ResultVO(10000, "注册成功！", null);
            } else {
                return new ResultVO(10002, "注册失败！", null);
            }
        } else {
            return new ResultVO(10001, "用户名已经被注册！", null);
        }
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public ResultVO1 getAllUsers(PageVo pageVo) {
        System.out.println("pageVo:" + pageVo);
        PageHelper.startPage(pageVo.getPage(),pageVo.getLimit());
        List<Users> users = usersMapper.selectAll();
        List<Users> userList = new ArrayList<>();
        for (Users users1 : users){
            userList.add(users1);
        }

        userList.forEach(System.out::println);



        DecimalFormat df=new DecimalFormat("0.00");
        String format = df.format((float)userDao.selectCount()/pageVo.getLimit());
        double v = Double.parseDouble(format);

        int i = (int)Math.ceil(v);

        PageInfo pageInfo = new PageInfo(userList);
        pageInfo.setPages(i);
        pageInfo.setTotal(userDao.selectCount());
        System.out.println("------>" + pageInfo);
        List<Users> users1 = usersMapper.selectAll();
        return new ResultVO1(ResStatus.OK,users1,pageInfo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVO delectUsersById(Integer users) {

        int i = usersMapper.deleteByPrimaryKey(users);
        System.out.println(i);
        if (i>0){
            return new ResultVO(ResStatus.OK,"删除成功","");
        }

        return new ResultVO(ResStatus.NO,"fail","");

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVO addUsers(Users user) {

//        log.info("userService接收参数：{},{}",user,source);
        String realpath = "D:\\upload\\imgs\\headPortrait";

//        String uniFileName = null;
//        try {
//            String filename = source.getOriginalFilename();
//
//            //定制全局唯一的命名
//            String unique = UUID.randomUUID().toString();
//
//            //获得文件的后缀
//            String ext = FilenameUtils.getExtension(filename);
//
//            //定制全局唯一的文件名
//            uniFileName = unique + "." + ext;
//            log.info("头像的文件名为:{}",uniFileName);
//
//            File file = new File(realpath);
//            if (!file.exists()){
//                file.mkdirs();
//            }
//
//            source.transferTo(new File(realpath+"\\"+uniFileName));
//            log.info("头像的存储路径为:{}",realpath+"\\"+uniFileName);
//            String img_url = "headPortrait/" + uniFileName;
//
//            user.setUserImg(img_url);
//
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        System.out.println("新增的用户：" + user);

        int insert = usersMapper.insert(user);
        if (insert>0){
            return new ResultVO(ResStatus.OK,"添加成功",null);
        }else{
            return new ResultVO(ResStatus.NO,"添加失败",null);
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVO updateUser(Users user) {
        Integer i = usersMapper.updateUser(user);
        return i == 1 ? new ResultVO(ResStatus.OK, "修改成功", i) : new ResultVO(ResStatus.NO, "修改失败", i);
    }

    @Override
    public ResultVO getall() {
        List<User> users = userDao.selectAll();
        System.out.println("vskdkjshd:" + users);
        ResultVO resultVO = new ResultVO(ResStatus.OK,"success",users);
        return resultVO;
    }


}
